using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LitJson2;
using Net.Common;
using Net.kcp;
using UnityEngine;

/****************************************************
// 功能：客户端请求网络 UDP(KCP)
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/17 16:10:12
*****************************************************/

public class ClientKcp : KcpClient
{
    private new KcpClient client;
    private static ClientKcp instance;
    private static readonly object lockObject = new object();

    private ClientKcp()
    {
    }

    public static ClientKcp Instance
    {
        get
        {
            lock (lockObject)
            {
                if (instance == null)
                {
                    instance = new ClientKcp();
                }
            }

            return instance;
        }
    }

    /// <summary>
    /// 开启Kcp监听
    /// </summary>
    public void Connect()
    {
        client = new ClientKcp();
        client.NoDelay(1, 5, 2, 1); //fast
        client.WndSize(64, 64);
        //client.Timeout(50 * 1000);
        client.SetMtu(1200);
        client.SetMinRto(50);
        client.SetConv(ModelManager.Instance.conv);
        client.Connect(Constants.KCP_ADDRESS, Constants.KCP_PORT);
        client.Start();
    }

    /// <summary>
    /// 处理收到的消息
    /// </summary>
    /// <param name="result"></param>
    protected override void HandleReceive(ByteBuf result)
    {
        var content = Encoding.UTF8.GetString(result.GetRaw());
        var jsonData = JsonMapper.ToObject(content);
        
        ClientTcp.Instance.HandleTcpMsgInfo((RequestType)Enum.Parse(typeof(RequestType), jsonData["requestType"].ToJson()), (string) jsonData["data"]);
    }

    protected override void HandleException(Exception e)
    {
        //base.HandleException(ex);

        if (e is SocketException { SocketErrorCode: SocketError.ConnectionRefused })
        {
            Debug.LogError("连接KCP服务器失败，请检查网络状况");
            ClientTcp.Instance.HandleTcpMsgInfo(RequestType.CONNECTION_REFUSED, "连接KCP服务器失败，请检查网络状况");
            ModelManager.Instance.isConnected = false;
        }
        else
        {
            Debug.LogError($"接收KCP发送的消息失败：{e.Message}");

        }
    }

    protected override void HandleTimeout()
    {
        base.HandleTimeout();
        Debug.Log("KCP超时");
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="msg"></param>
    public void Send(MsgInfo msg)
    {
        if (SimulateController.Instance.isActive)
        {
            // 这是模拟战斗数据
            SimulateController.Instance.SimulateServerMsg(msg);
            return;
        }
        var data = new ByteBuf(Encoding.UTF8.GetBytes(JsonMapper.ToJson(msg)));
        client.Send(data);
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    public void Disconnect()
    {
        Debug.LogError("非正常关闭应用 - KCP");

        client.Stop();
    }
}
